<template>
  <div class="map-page">
    <div v-if="reload" ref="dom" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from "echarts"
import { ref, watchEffect, defineProps } from "vue"
import API from '@/common/api'

const props = defineProps({
  TestMainId: {
    type: String,
    default: ''
  },
  companyLabFlag: {
    type: Number,
    default: 0
  },
})
const dom = ref(null)
const reload = ref(false)
const legend = ref([])

const GetExcellentDataChartFun = async () => {
  const info = localStorage.getItem('info')
  if (info) {
    const res: any = await API.GetExcellentDataChart({
      "TestMainId": props.TestMainId, // 登录返回的，选2023，就把对应的该字段传进来
      "LabFlag": 1, // 传1 表示总部 
    })
    if (res.Tag) {
      const datas = res.Data.CompanyCount.map((company, index) => {
        const totalCount = company.TotalCount;
        const excellentCount = res.Data.CompanyExcellentCount[index].TotalCount;
        legend.value = res.Data.CompanyExcellentCount.map(e => e.CompanyName)
        const normalCount = totalCount - excellentCount;

        return [
          { name: "null", value: excellentCount },
          { name: "优秀数量", value: normalCount }
        ];
      });
      console.log("----------", JSON.stringify(datas));

      initCharts(datas)
    }
  }
}
const GetLocalExcellentDataChartFun = async () => {
  const info = localStorage.getItem('info')
  if (info) {
    const json = JSON.parse(info)
    const res: any = await API.GetLocalExcellentDataChart({
      "TestMainId": props.TestMainId, // 登录返回的，选2023，就把对应的该字段传进来
      "LabFlag": props.companyLabFlag, // 传1 表示总部 
      "LabId": json.Id,
      "LabType": json.LabType,
      "LabName": json.ShortName,
    })
    if (res.Tag) {
      legend.value = res.Data.CompanyCount.map(e => e.CompanyName)
      const datas = res.Data.CompanyCount.map((company) => {
        const totalCount = company.TotalCount;
        const name = company.CompanyName
        const index = res.Data.CompanyExcellentCount.findIndex(e => e.CompanyName === name)
        const excellentCount = res.Data.CompanyExcellentCount[index].TotalCount;
        const normalCount = totalCount - excellentCount;

        return [
          { name: "null", value: excellentCount },
          { name: "优秀数量", value: normalCount }
        ];
      });

      initCharts(datas)
    }
  }
}
const initCharts = (datas) => {
  const charts = echarts.init(dom.value)
  const colorList = {
    中国航油: ["#E44954", "#C4232A"],
    中国石化: ["#E3BD81", "#C3884A"],
    中国石油: ["#0A4FE8", "#06348F"],
    其他: ["#86F280", "#4EE049"],
  }

  function getColor(name) {
    if (Object.hasOwnProperty.call(colorList, name)) {
      return colorList[name][0];
    } else {
      // 随机生成颜色
      return "#" + Math.floor(Math.random() * 16777215).toString(16);
    }
  }
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        const itemName = params.name;
        const itemValue = params.value;
        const percentage = params.percent + '%';
        if (params.dataIndex === 0) {
          return `${itemName} 优秀数量 : ${itemValue} (${percentage})`;
        } else {
          return ``;
        }
      }
    },
    legend: {
      textStyle: {
        color: '#fff'
      },
      type: 'plain',
      left: 'center',
      top: 0,
      data: legend.value // 使用公司名称作为图例数据
    },
    series: datas.map((data, idx) => {
      const isFirst = idx % 2
      const companyName = legend.value[idx]
      return {
        type: "pie",
        radius: [20, 45],
        top: idx < 2 ? 30 : 155,
        height: "40%",
        left: isFirst === 0 ? -100 : 100,
        width: 420,
        itemStyle: {
          borderColor: "#4996dd",
          borderWidth: 5, // 设置边框宽度为 5px
          shadowBlur: 0, // 设置阴影模糊度为 3，调整这个参数以控制阴影的清晰度
          shadowColor: '#5b9ad4', // 设置阴影颜色为 #4996dd
          shadowOffsetX: 0, // 设置阴影水平偏移量为 0
        },
        // label: {
        //   show: true,
        //   formatter: `{d}%`,
        //   color: "#ffffff",
        // },
        label: {
          show: true,
          formatter: function (params) {
            if (params.dataIndex === 1) {
              return '';
            }
            return `{a|${params.value}}\n{b|${params.percent}%}`; // 仅显示优秀数量
          },
          rich: {
            a: { color: '#fff', fontSize: 14 },
            b: { color: '#fff', fontSize: 12 }
          },
        },
        data: data.map(item => {
          return {
            ...item,
            name: companyName, // 设置数据的名称为公司名称
            itemStyle: {
              color: item.name !== "null" ? "#5aa2e0" : getColor(companyName) // 设置颜色为 #5aa2e0 如果是null，否则使用原来的颜色
            }
          }
        })
      }
    }),
  }
  charts.setOption(option)
}

watchEffect(() => {
  console.log(props.TestMainId);
  reload.value = false
  setTimeout(() => {
    reload.value = true
    if (props.companyLabFlag === 1) {
      GetExcellentDataChartFun()
    } else {
      GetLocalExcellentDataChartFun()
    }
  }, 500);

})
</script>

<style scoped>
.map-page {
  height: 100%;
  width: 100%;
  color: #77a4cf;
}
</style>
